package com.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.entity.MessageNotice;
import com.example.entity.Promotion;
import com.example.entity.PromotionRecord;
import com.example.entity.check.SelfCheck;
import com.example.entity.check.SelfCheckResult;
import com.example.ext.entity.ExtElevator;
import com.example.mapp.*;
import com.example.service.SelfCheckService;
import com.example.util.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by simon on 2018/5/29.
 */
@Service
public class SelfCheckServiceImpl implements SelfCheckService {

	private final static Logger logger = (Logger) LoggerFactory.getLogger(SelfCheckServiceImpl.class);

	@Autowired
	private SelfCheckMapp selfCheckMapp;

	@Autowired
	private SelfCheckResultMapp selfCheckResultMapp;

	@Autowired
	private ElevatorMapp elevatorMapp;

	@Autowired
	private MessageNoticeMapp messageNoticeMapp;

	@Autowired
	private PromotionMapp promotionMapp;

	@Autowired
	private Environment environment;

	@Override
	@Transactional
	public Map<String, Object> add(SelfCheck selfCheck) {

		try{
			int i = selfCheckMapp.add(selfCheck);
			long insertId = selfCheck.getId();
			List<SelfCheckResult> list = selfCheck.getCheckResults();
			if(!CollectionUtils.isEmpty(list)){
				for(SelfCheckResult result : list){
					result.setSelfCheckId(String.valueOf(insertId));
				}
			}

			//批量插入年检检查项结果
			selfCheckResultMapp.add(list);

			//生成年度自检报告
			exportInspectReport(selfCheck);

			if(i > 0){
				ExtElevator extElevator = elevatorMapp.queryById(selfCheck.getElevatorId() + "");
				addEmpiric(extElevator, 50, "提交1份年度自检记录", true, 1);
				String content = "设备代码为："
						+ extElevator.getElevatorNum() + " 的电梯，年度自检已完成，请您及时去确认。";
				String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

				MessageNotice msg = new MessageNotice();
				msg.setTitle("电梯年度自检确认通知");
				msg.setElevatoriMonId(selfCheck.getId().toString());
				msg.setElevatoriType("11");
				msg.setContent(content);
				msg.setReceiveUserId(String.valueOf(extElevator.getSafeUserId()));
				msg.setIsRead("0");
				msg.setNoticeTime(noticeTime);
				msg.setReceivePartyId(String.valueOf(extElevator.getUsedPartyId()));
				messageNoticeMapp.add(msg);

				return ResultUtil.returnSuccess("提交成功",null);
			}else{
				return ResultUtil.returnSuccess("提交失败",null);
			}
		}catch (Exception e){
			logger.error("自检添加失败："+e.getMessage(),e);
			return ResultUtil.returnSuccess("新增失败",null);
		}
	}

	private void addEmpiric(ExtElevator extElevator, Integer empiricValue, String content, boolean flag, Integer times) throws Exception {
		/*int realTimes1 = 0;
		int realTimes2 = 0;
		if (flag) {
			Map<String, Object> param1 = new HashMap<>();
			param1.put("userId", extElevator.getMaintenanceUserFirst());
			param1.put("type", "4");
			param1.put("addedTime", new SimpleDateFormat("yyyy").format(new Date()));
			param1.put("type", content);
			realTimes1 = promotionMapp.findAddTimes(param1);

			Map<String, Object> param2 = new HashMap<>();
			param2.put("userId", extElevator.getMaintenanceUserSecond());
			param2.put("type", "4");
			param2.put("addedTime", new SimpleDateFormat("yyyy").format(new Date()));
			param2.put("type", content);
			realTimes2 = promotionMapp.findAddTimes(param2);
		}
		if (extElevator.getMaintenanceUserFirst() != null && (!flag || times >= realTimes1)) {
			Map<String, Object> map = new HashMap<>();
			map.put("type", "4");
			map.put("userId", extElevator.getMaintenanceUserFirst());
			Promotion promotion2 = promotionMapp.findById(map);
			if (null != promotion2 && promotion2.getId() != null) {
				promotion2 = PromotionUtil.calc(promotion2, "4", empiricValue, false);
				promotionMapp.update(promotion2);
			} else {
				promotion2 = new Promotion();
				promotion2.setType("4");
				promotion2.setUserId(extElevator.getMaintenanceUserFirst().toString());
				promotion2 = PromotionUtil.calc(promotion2, "4", empiricValue, true);
				promotionMapp.insert(promotion2);
			}
			PromotionRecord promotionRecord = new PromotionRecord();
			promotionRecord.setUserId(promotion2.getUserId());
			promotionRecord.setType(promotion2.getType());
			promotionRecord.setEmpiricItem(content);
			promotionRecord.setAddedTime(PromotionUtil.getTime());
			promotionRecord.setEmpiricValue(empiricValue);
			promotionMapp.insertRecord(promotionRecord);
		}
		if (extElevator.getMaintenanceUserSecond() != null && (!flag || times >= realTimes2)) {
			Map<String, Object> map = new HashMap<>();
			map.put("type", "4");
			map.put("userId", extElevator.getMaintenanceUserSecond());
			Promotion promotion2 = promotionMapp.findById(map);
			if (null != promotion2 && promotion2.getId() != null) {
				promotion2 = PromotionUtil.calc(promotion2, "4", empiricValue, false);
				promotionMapp.update(promotion2);
			} else {
				promotion2 = new Promotion();
				promotion2.setType("4");
				promotion2.setUserId(extElevator.getMaintenanceUserSecond().toString());
				promotion2 = PromotionUtil.calc(promotion2, "4", empiricValue, true);
				promotionMapp.insert(promotion2);
			}
			PromotionRecord promotionRecord = new PromotionRecord();
			promotionRecord.setUserId(promotion2.getUserId());
			promotionRecord.setType(promotion2.getType());
			promotionRecord.setEmpiricItem(content);
			promotionRecord.setAddedTime(PromotionUtil.getTime());
			promotionRecord.setEmpiricValue(empiricValue);
			promotionMapp.insertRecord(promotionRecord);
		}*/
	}

	@Override
	public Map<String, Object> queryList(SelfCheck selfCheck) {
		List<SelfCheck> list = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Page<SelfCheck> page = PageHelper.startPage(selfCheck.getCurrentPage(),
					selfCheck.getPageSize());
			list = selfCheckMapp.queryList(selfCheck);
			map.put("list", list);
			map.put("total", page.getTotal());
		} catch (Exception e) {
			logger.error(e.getMessage());
			return ResultUtil.returnError("查询失败" + e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("查询成功", map);
	}

	@Override
	public Map<String, Object> queryById(String id) {
		SelfCheck selfCheck = null;
		try {
			selfCheck = selfCheckMapp.queryById(id);
		}catch (Exception e){
			logger.error(e.getMessage());
			return ResultUtil.returnError("查询详情失败",null);
		}
		return ResultUtil.returnSuccess("成功",selfCheck);
	}

	/**
	 * 导出各电梯年检报告
	 * @param selfCheck
	 * @return
	 */
	public Map<String, Object> exportInspectReport(SelfCheck selfCheck) throws Exception{
		Map<String,Object> resultMap  = new HashMap<>();
        Map<String,String> templateMap = new HashMap<>();

        /**
         * 1、组织数据 1、电梯相关数据 2、使用单位相关数据 3、维保单位数据
         */
        ExtElevator extElevator = elevatorMapp.queryById(selfCheck.getElevatorId());
        getElevatorData(extElevator,templateMap);

        /**
         * 2、获取检查项数据
         */
        getCheckItemsResult(selfCheck,templateMap,extElevator.getElevatorTypeId());

        /**
         * 3、获取对应报告模板，生成文件
         */

        String fileUrl = dataToFile(templateMap,extElevator.getElevatorTypeId());

        /**
         * 4、生成文件的路径 更新到表里
         */
        selfCheck.setReportUrl(fileUrl);
        selfCheckResultMapp.updateReportUrl(selfCheck);

		return ResultUtil.returnSuccess("成功", resultMap);

	}

	/**
	 * 1、获取电梯、使用单位、维保单位等数据
	 * @param extElevator
	 * @param templateMap
	 * @throws Exception
	 */
	private void getElevatorData(ExtElevator extElevator,Map<String,String> templateMap) throws Exception{
		templateMap.put("usedPartyName",extElevator.getUsedPartyName() != null ? extElevator.getUsedPartyName() : "");
		templateMap.put("maintenancePartyName",extElevator.getMaintenancePartyName() != null ? extElevator.getMaintenancePartyName() : "");
		templateMap.put("elevatorNum",extElevator.getElevatorNum() != null ? extElevator.getElevatorNum() : "");
		templateMap.put("creditCode",extElevator.getCreditCode() != null ? extElevator.getCreditCode() : ""); //使用单位代码  新增
		templateMap.put("buildAddr",extElevator.getBuildAddr() != null ? extElevator.getBuildAddr() : ""); //设备使用地点
		templateMap.put("innerId",extElevator.getInnerId() != null ? extElevator.getInnerId() : ""); //单位内编号
		templateMap.put("safeUserName",extElevator.getSafeUserName());//安全管理人员  新增
		templateMap.put("safeUserTel",extElevator.getSafeUserTel() != null ? extElevator.getSafeUserTel() : "");//联系电话
		templateMap.put("createCompanyName",extElevator.getCreateCompanyName() != null ? extElevator.getCreateCompanyName() : "");//制造单位名称
        if(extElevator.getElevatorNum() != null && extElevator.getElevatorNum().length() >= 20){
            Date date = new SimpleDateFormat("yyyyMM").parse(extElevator.getElevatorNum().substring(10,16));
            templateMap.put("makeDate",new SimpleDateFormat("yyyy年MM月").format(date));//制造日期
        }

		templateMap.put("lastMaintenancePartyName",extElevator.getMaintenancePartyName() != null ? extElevator.getMaintenancePartyName() : "");//最近一次改造单位
		templateMap.put("lastMaintenanceTime",extElevator.getLastMaintenanceTime() != null ? extElevator.getLastMaintenanceTime() : "");//最近一次改造日期
		templateMap.put("elevatorModel",extElevator.getElevatorModel() != null ? extElevator.getElevatorModel() : "");//型   号
		templateMap.put("serialNum",extElevator.getSerialNum() != null ? extElevator.getSerialNum() : "");//产品编号
		templateMap.put("rescuePhoneNum",extElevator.getRescuePhoneNum() != null ? extElevator.getRescuePhoneNum() : "");//应急救援电话
		templateMap.put("ratedLoad",extElevator.getRatedLoad() != null ? extElevator.getRatedLoad() : "");//额定载重量
		templateMap.put("runSpeed",extElevator.getRunSpeed() != null ? extElevator.getRunSpeed() : "");//额定速度
	}

	/**
	 * 2、获取年检结果数据
	 * @param selfCheck
	 */
	private void getCheckItemsResult(SelfCheck selfCheck,Map<String,String> templateMap, long elevatorTypeId) throws Exception{
		List<Map<String,Object>> result = selfCheckResultMapp.queryCheckResult(selfCheck);

		/**
		 * 获取基本填空项参数
		 */
        templateMap.put("checkTime","");
		if(selfCheck.getCheckTime() != null){
            Date date = new SimpleDateFormat("yyyyMMdd").parse(selfCheck.getCheckTime().substring(0,8));
            templateMap.put("checkTime",new SimpleDateFormat("yyyy年MM月dd日").format(date));
        }
		templateMap.put("useRegistCertiNumber",selfCheck.getUseRegistCertiNumber() != null ? selfCheck.getUseRegistCertiNumber() : "");//使用登记证编号
		templateMap.put("layer",selfCheck.getLayer() != null ? selfCheck.getLayer() : "");
		templateMap.put("station",selfCheck.getStation() != null ? selfCheck.getStation() : "");
		templateMap.put("door",selfCheck.getDoor() != null ? selfCheck.getDoor() : "");
		templateMap.put("controlMode",selfCheck.getControlMode() != null ? selfCheck.getControlMode() : "");
		templateMap.put("driverHostNumber",selfCheck.getDriverHostNumber() != null ? selfCheck.getDriverHostNumber() : "");
		templateMap.put("controlScreenNumber",selfCheck.getControlScreenNumber() != null ? selfCheck.getDriverHostNumber() : "");
		templateMap.put("carSpeedLimiterModel",selfCheck.getCarSpeedLimiterModel() != null ? selfCheck.getCarSpeedLimiterModel() : "");
		templateMap.put("carSpeedLimiterNumber",selfCheck.getCarSpeedLimiterNumber() != null ? selfCheck.getCarSpeedLimiterNumber() : "");
		templateMap.put("dualSpeedLimiterModel",selfCheck.getDualSpeedLimiterModel() != null ? selfCheck.getDualSpeedLimiterModel() : "");
		templateMap.put("dualSpeedLimiterNumber",selfCheck.getDualSpeedLimiterNumber() != null ? selfCheck.getDualSpeedLimiterNumber() : "");
		if("0".equals(selfCheck.getIsPass())){
            templateMap.put("isPass","不合格");
        }
		if("1".equals(selfCheck.getIsPass())){
            templateMap.put("isPass","合格");
        }

		/**
		 * 分别获取各电梯填空项
		 */
		if(elevatorTypeId == 1 || elevatorTypeId == 5){
			//限速器校验日期
			templateMap.put("speedLimiterCaliDate",selfCheck.getSpeedLimiterCaliDate() != null ? selfCheck.getSpeedLimiterCaliDate() : "");

			//设备品种
			String equipmentVariety = selfCheck.getEquipmentVariety();
			if("1".equals(equipmentVariety)){
				equipmentVariety = "√曳引驱动乘客电梯  □曳引驱动载货电梯\n" +
						"□强制驱动载货电梯";
			}else if ("2".equals(equipmentVariety)){
				equipmentVariety = "□曳引驱动乘客电梯  √曳引驱动载货电梯\n" +
						"□强制驱动载货电梯";
			}else if ("3".equals(equipmentVariety)){
				equipmentVariety = "□曳引驱动乘客电梯  □曳引驱动载货电梯\n" +
						"√强制驱动载货电梯";
			}else{
				equipmentVariety = "□曳引驱动乘客电梯  □曳引驱动载货电梯\n" +
						"□强制驱动载货电梯";
			}
			templateMap.put("equipmentVariety",equipmentVariety);

			//设备类型
			String equipmentType = selfCheck.getEquipmentType();
			if("1".equals(equipmentType)){
				equipmentType = "√有机房      □无机房";
			}else if("2".equals(equipmentType)){
				equipmentType = "□有机房      √无机房";
			}else{
				equipmentType = "□有机房      □无机房";
			}
			templateMap.put("equipmentType",equipmentType);

		}
		else if (elevatorTypeId == 4 || elevatorTypeId == 6){
			templateMap.put("nominalSpeed", selfCheck.getNominalSpeed() != null ? selfCheck.getNominalSpeed() : "");
			templateMap.put("nominalWidth", selfCheck.getNominalWidth() != null ? selfCheck.getNominalWidth() : "");
			templateMap.put("inclinationAngle", selfCheck.getInclinationAngle() != null ? selfCheck.getInclinationAngle() : "");
			templateMap.put("conveyingCapacity", selfCheck.getConveyingCapacity() != null ? selfCheck.getConveyingCapacity() : "");
			templateMap.put("liftingHeight", selfCheck.getLiftingHeight() != null ? selfCheck.getLiftingHeight() : "");
			templateMap.put("lengthOfUseArea", selfCheck.getLengthOfUseArea() != null ? selfCheck.getLengthOfUseArea() : "");
			templateMap.put("controlCabinetNumber",selfCheck.getControlCabinetNumber() != null ? selfCheck.getControlCabinetNumber() : "");
			//设备品种
			String equipmentVariety = selfCheck.getEquipmentVariety();
			if("1".equals(equipmentVariety)){
				equipmentVariety = "√自动扶梯  □自动人行道";
			}else if ("2".equals(equipmentVariety)){
				equipmentVariety = "□自动扶梯  √自动人行道";
			}else{
				equipmentVariety = "□自动扶梯  □自动人行道";
			}
			templateMap.put("equipmentVariety",equipmentVariety);

			//设备类型
			String equipmentType = selfCheck.getEquipmentType();
			if("1".equals(equipmentType)){
				equipmentType = "√室内普通型   □室内公共交通型\n" +
						"□室外普通型   □室外公共交通型";
			}else if("2".equals(equipmentType)){
				equipmentType = "□室内普通型   √室内公共交通型\n" +
						"□室外普通型   □室外公共交通型";
			}else if("3".equals(equipmentType)){
				equipmentType = "□室内普通型   □室内公共交通型\n" +
						"√室外普通型   □室外公共交通型";
			}else if("4".equals(equipmentType)){
				equipmentType = "□室内普通型   □室内公共交通型\n" +
						"□室外普通型   √室外公共交通型";
			}else{
				equipmentType = "□室内普通型   □室内公共交通型\n" +
						"□室外普通型   □室外公共交通型";
			}
			templateMap.put("equipmentType",equipmentType);

		}
		else if(elevatorTypeId == 2){ // 液压
			templateMap.put("ratedLoad",selfCheck.getRatedLoad() != null ? selfCheck.getRatedLoad() : "");
			templateMap.put("uplinkRatedSpeed",selfCheck.getUplinkRatedSpeed() != null ? selfCheck.getUplinkRatedSpeed() : "");
			templateMap.put("downwardRatedSpeed",selfCheck.getDownwardRatedSpeed() != null ? selfCheck.getDownwardRatedSpeed() : "");
			templateMap.put("numberOfCylinders",selfCheck.getNumberOfCylinders() != null ? selfCheck.getDownwardRatedSpeed() : "");
			//设备品种
			String equipmentVariety = selfCheck.getEquipmentVariety();
			if("1".equals(equipmentVariety)){
				equipmentVariety = "√液压乘客电梯  \n" +
						"□液压载货电梯";
			}else if ("2".equals(equipmentVariety)){
				equipmentVariety = "□液压乘客电梯  \n" +
						"√液压载货电梯";
			}else{
				equipmentVariety = "□液压乘客电梯  \n" +
						"□液压载货电梯";
			}
			templateMap.put("equipmentVariety",equipmentVariety);

			String jackUpPattern = selfCheck.getJackUpPattern();
			if("1".equals(jackUpPattern)){
				jackUpPattern = "√直接     □间接";
			}else if("2".equals(jackUpPattern)){
				jackUpPattern = "□直接     √间接";
			}else {
				jackUpPattern = "□直接     □间接";
			}
			templateMap.put("jackUpPattern",jackUpPattern);

			String controlMode = selfCheck.getControlMode();
			if("1".equals(controlMode)){
				controlMode = "√集选  □并联  □群控\n" +
						"□信号  □按钮  □手柄";
			}else if("2".equals(controlMode)){
				controlMode = "□集选  √并联  □群控\n" +
						"□信号  □按钮  □手柄";
			}else if("3".equals(controlMode)){
				controlMode = "□集选  □并联  √群控\n" +
						"□信号  □按钮  □手柄";
			}else if("4".equals(controlMode)){
				controlMode = "□集选  □并联  □群控\n" +
						"√信号  □按钮  □手柄";
			}else if("5".equals(controlMode)){
				controlMode = "□集选  □并联  □群控\n" +
						"□信号  √按钮  □手柄";
			}else if("6".equals(controlMode)){
				controlMode = "□集选  □并联  □群控\n" +
						"□信号  □按钮  √手柄";
			}else{
				controlMode = "□集选  □并联  □群控\n" +
						"□信号  □按钮  □手柄";
			}
			templateMap.put("controlMode",controlMode);

			String isNeedSafetyManager = selfCheck.getIsNeedSafetyManager();
			if("1".equals(isNeedSafetyManager)){
				isNeedSafetyManager = "√是     □否";
			}else if("2".equals(isNeedSafetyManager)){
				isNeedSafetyManager = "□是     √否";
			}else{
				isNeedSafetyManager = "□是     □否";
			}
			templateMap.put("isNeedSafetyManager",isNeedSafetyManager);

		}
		else if(elevatorTypeId == 3){ // 杂货
			templateMap.put("overflowPressure",selfCheck.getOverflowPressure() != null ? selfCheck.getOverflowPressure() : "");
			templateMap.put("noOrFullLoadPressure",selfCheck.getNoOrFullLoadPressure() != null ? selfCheck.getNoOrFullLoadPressure() : "");
			templateMap.put("speedLimiterNextConfDate",selfCheck.getSpeedLimiterNextConfDate() != null ? selfCheck.getSpeedLimiterNextConfDate() : "");
			templateMap.put("elevatorNextInspDate",selfCheck.getElevatorNextInspDate() != null ? selfCheck.getElevatorNextInspDate() : "");

			String equipmentType = selfCheck.getEquipmentType();
			if("1".equals(equipmentType)){
				equipmentType = "√曳引式 □强制式 □液压式";
			}else if("2".equals(equipmentType)){
				equipmentType = "□曳引式 √强制式 □液压式";
			}else if("3".equals(equipmentType)){
				equipmentType = "□曳引式 □强制式 √液压式";
			}else{
				equipmentType = "□曳引式 □强制式 □液压式";
			}
			templateMap.put("equipmentType",equipmentType);
		}

		for(int i = 0,len = result.size(); i < len ; i++){
			Map<String,Object> checkItemMap = result.get(i);
			String itemKey = checkItemMap.get("itemKey") + "";
			Map<String,Object> valueMap = (Map) JSON.parse(checkItemMap.get("itemValue") + "");

			if(Boolean.valueOf(valueMap.get("isOk")+"")){
				templateMap.put(itemKey+"1","√");
				templateMap.put(itemKey+"2","合格");
			}else if(valueMap.get("isOk") == null){ //标识无此项
				templateMap.put(itemKey+"1","/");
				templateMap.put(itemKey+"2","/");
			}else{
				templateMap.put(itemKey+"1","×");
				templateMap.put(itemKey+"2","不合格");
			}
			if(elevatorTypeId == 1 || elevatorTypeId == 5){
				fillInBlanksTraction(templateMap,valueMap,itemKey);
			}else if(elevatorTypeId == 4 || elevatorTypeId == 6){
				fillInBlanksEscalator(templateMap,valueMap,itemKey);
			}else if(elevatorTypeId == 2){
				fillInBlanksHydraulic(templateMap,valueMap,itemKey);
			}else if(elevatorTypeId == 3){
				fillInBlanksImpurity(templateMap,valueMap,itemKey);
			}
		}

	}

	/**
	 * 3、获取报告模板，生成文件
	 * @param templateMap
	 * @return
	 */
	private String dataToFile(Map<String,String> templateMap, long elevatorTypeId) throws Exception{

		// 1.获取保存路径，不存在则创建
		String path = environment.getProperty("upload", String.class);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String dateString = sdf.format(new Date());
		if (path.endsWith(Constants.FILE_SEPARATOR)) {
			path = path + dateString + Constants.FILE_SEPARATOR;
		} else {
			path = path + Constants.FILE_SEPARATOR + dateString + Constants.FILE_SEPARATOR;
		}
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
		// 重现生成文件名，防止中文乱码
		String fileName = UUID.randomUUID() + ".docx";
		// 填充完数据的临时xml
		String xmlTemp = System.getProperty("java.io.tmpdir") + UUID.randomUUID() + ".xml";
		File temp = new File(xmlTemp);
		path = path + fileName;
		String fileUrl = dateString + Constants.FILE_SEPARATOR + fileName;
		try {
//			String xmlTemplate = ""; // xml的文件名
//			String docxTemplate = ""; // docx的路径和文件名

//			if(elevatorTypeId == 1 || elevatorTypeId == 5){
//				xmlTemplate = "traction_annualInspection.xml";
//				docxTemplate = environment.getProperty("TEMPLATES",String.class)+ "/traction_annualInspection.docx";
//			}else if(elevatorTypeId == 4 || elevatorTypeId == 6){
//				xmlTemplate = "escalator_annualInspection.xml";
//				docxTemplate = environment.getProperty("TEMPLATES",String.class)+ "/escalator_annualInspection.docx";
//			}else if(elevatorTypeId == 3){
//				xmlTemplate = "impurity_annualInspection.xml";
//				docxTemplate = environment.getProperty("TEMPLATES",String.class)+ "/impurity_annualInspection.docx";
//			}else if(elevatorTypeId == 2){
//				xmlTemplate = "hydraulic_annualInspection.xml";
//				docxTemplate = environment.getProperty("TEMPLATES",String.class)+ "/hydraulic_annualInspection.docx";
//			}
//
//			// 目标文件名
//			String toFilePath = path;
//
//			Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(temp), "UTF-8"));
//
//			// 2.把map中的数据动态由freemarker传给xml
//			XmlFill.process(xmlTemplate, templateMap, w,environment);
//			FileOutputStream fileOutputStream = new FileOutputStream(toFilePath);
			// 3.把填充完成的xml写入到docx中
//			XmlToDocx.outDocx(temp, docxTemplate, fileOutputStream);
			String docxStr = null;
			if(elevatorTypeId == 1 || elevatorTypeId == 5){
				docxStr =  "/traction_annualInspection.docx";
			}else if(elevatorTypeId == 4 || elevatorTypeId == 6){
				docxStr = "/escalator_annualInspection.docx";
			}else if(elevatorTypeId == 3){
				docxStr = "/impurity_annualInspection.docx";
			}else if(elevatorTypeId == 2){
				docxStr = "/hydraulic_annualInspection.docx";
			}
            XmlFill.poiExportNewWord(path,templateMap,null,environment,docxStr);
		} catch (Exception e) {
			logger.error("根据模板获取年检报告出现异常。"+e.getMessage(),e);
			throw e;
		} finally {
			temp.delete();
		}
		return fileUrl;
	}

	/**
	 * 曳引电梯，处理检查项中的填空项
	 * @param templateMap
	 * @param valueMap
	 * @param itemKey
	 */
	private void fillInBlanksTraction(Map<String,String> templateMap,Map<String,Object> valueMap,String itemKey){
		if("twoPointOneOne".equals(itemKey) || "twoPointOneThree".equals(itemKey) ||
				"twoPointNineTwo".equals(itemKey) || "twoPointEleven".equals(itemKey) ||
				"threeSevenOne".equals(itemKey) || "threeSevenTwo".equals(itemKey) ||
				"threeFifteenFive".equals(itemKey) || "fourNine".equals(itemKey) ||
				"fourTen".equals(itemKey) || "fiveOneOneThree".equals(itemKey) ||
				"sixThreeOne".equals(itemKey) || "sixThreeTwo".equals(itemKey) ||
				"sixNineOneThree".equals(itemKey) || "sixTwelve".equals(itemKey) ||
				"eightOne".equals(itemKey) ){
			if("twoPointOneOne".equals(itemKey)){
				templateMap.put("floorHeight",valueMap.get("floorHeight") + "");
				templateMap.put("ladderHeight",valueMap.get("ladderHeight") + "");
				templateMap.put("includedAngle",valueMap.get("includedAngle") + "");
				return;
			}
			if("twoPointOneThree".equals(itemKey)){
				templateMap.put("doorWidth",valueMap.get("doorWidth") + "");
				templateMap.put("doorHeight",valueMap.get("doorHeight") + "");
				return;
			}
			if("twoPointNineTwo".equals(itemKey)){
				templateMap.put("waitTime",valueMap.get("waitTime") + "");
				return;
			}
			if("twoPointEleven".equals(itemKey)){
				templateMap.put("nominalVoltage1",valueMap.get("nominalVoltage1") + "");
				templateMap.put("nominalVoltage2",valueMap.get("nominalVoltage2") + "");
				templateMap.put("nominalVoltage3",valueMap.get("nominalVoltage3") + "");
				templateMap.put("insulationResistance1",valueMap.get("insulationResistance1") + "");
				templateMap.put("insulationResistance2",valueMap.get("insulationResistance2") + "");
				templateMap.put("insulationResistance3",valueMap.get("insulationResistance3") + "");
				return;
			}
			if("threeSevenOne".equals(itemKey)){
				templateMap.put("spacing",valueMap.get("spacing") + "");
				return;
			}
			if("threeSevenTwo".equals(itemKey)){
				templateMap.put("localHeight",valueMap.get("localHeight") + "");
				templateMap.put("distance",valueMap.get("distance") + "");
				return;
			}
			if("threeFifteenFive".equals(itemKey)){
				templateMap.put("maxValue",valueMap.get("maxValue") + "");
				templateMap.put("measuredValue",valueMap.get("measuredValue") + "");
				return;
			}
			if("fourNine".equals(itemKey)){
				templateMap.put("verticalHeight",valueMap.get("verticalHeight") + "");
				templateMap.put("width",valueMap.get("width") + "");
				return;
			}
			if("fiveOneOneThree".equals(itemKey)){
				templateMap.put("diameterRatio",valueMap.get("diameterRatio") + "");
				return;
			}
			if("sixThreeOne".equals(itemKey)){
				templateMap.put("maxClearance1",valueMap.get("maxClearance1") + "");
				return;
			}
			if("sixThreeTwo".equals(itemKey)){
				templateMap.put("maxClearance2",valueMap.get("maxClearance2") + "");
				return;
			}
			if("sixNineOneThree".equals(itemKey)){
				templateMap.put("minValue1",valueMap.get("minValue1") + "");
				return;
			}
			if("sixTwelve".equals(itemKey)){
				templateMap.put("minValue2",valueMap.get("minValue2") + "");
				return;
			}
			if("eightOne".equals(itemKey)){
				templateMap.put("equilCoefficient",valueMap.get("equilCoefficient") + "");
				return;
			}
		}
	}

	/**
	 * 自动扶梯，处理检查项中填空项
	 * @param templateMap
	 * @param valueMap
	 * @param itemKey
	 */
	private void fillInBlanksEscalator(Map<String,String> templateMap,Map<String,Object> valueMap,String itemKey){
		if("tenTwo".equals(itemKey) || "tenThreeOne".equals(itemKey)
				|| "tenThreeTwo".equals(itemKey) || "twoNine".equals(itemKey)
				|| "threeOne".equals(itemKey) || "threeTwo".equals(itemKey)
				|| "threeFour".equals(itemKey) || "threeFive".equals(itemKey)
				|| "fourOne".equals(itemKey) || "fourTwoOne".equals(itemKey)
				|| "fourTwoTwo".equals(itemKey) || "fourTwoThree".equals(itemKey)
				|| "fourThree".equals(itemKey) || "fourFour".equals(itemKey)
				|| "fourSixOne".equals(itemKey) || "fourSixTwo".equals(itemKey)
				|| "fourSevenTwo".equals(itemKey) || "fourSevenThree".equals(itemKey)
				|| "fourSevenFour".equals(itemKey) || "fourSevenFive".equals(itemKey)
				|| "fourSevenSix".equals(itemKey) || "fourSevenSeven".equals(itemKey)
				|| "fiveOne".equals(itemKey) || "eightTwoOne".equals(itemKey)
				|| "eightTwoTwo".equals(itemKey)){

		}
		if("tenTwo".equals(itemKey)){
			templateMap.put("tolerance",valueMap.get("tolerance") + "");
			return;
		}
		if("tenThreeOne".equals(itemKey)){
			templateMap.put("brakingDistance1", valueMap.get("brakingDistance1") + "");
			return;
		}
		if("tenThreeTwo".equals(itemKey)){
			templateMap.put("brakingDistance2", valueMap.get("brakingDistance2") + "");
			return;
		}
		if("twoNine".equals(itemKey)){
			templateMap.put("nominalVoltage1",valueMap.get("nominalVoltage1") + "");
			templateMap.put("nominalVoltage2",valueMap.get("nominalVoltage2") + "");
			templateMap.put("nominalVoltage3",valueMap.get("nominalVoltage3") + "");
			templateMap.put("insulationResistance1",valueMap.get("insulationResistance1") + "");
			templateMap.put("insulationResistance2",valueMap.get("insulationResistance2") + "");
			templateMap.put("insulationResistance3",valueMap.get("insulationResistance3") + "");
			return;
		}
		if("threeOne".equals(itemKey)){
			templateMap.put("entrance",valueMap.get("entrance") + "");
			templateMap.put("exitus",valueMap.get("exitus") + "");
			return;
		}
		if("threeTwo".equals(itemKey)){
			templateMap.put("unblockedAreaWidth",valueMap.get("unblockedAreaWidth") + "");
			templateMap.put("depthDimension", valueMap.get("depthDimension") + "");
            if("1".equals(valueMap.get("isDanger"))){
                templateMap.put("isDanger","有危险 √ \n" +
                        "无危险 □");
            }else if("2".equals(valueMap.get("isDanger"))){
                templateMap.put("isDanger","有危险 □ \n" +
                        "无危险 √");
            }else{
                templateMap.put("isDanger","有危险 □ \n" +
                        "无危险 □");
            }
			templateMap.put("armBandHigher", valueMap.get("armBandHigher") + "");
			templateMap.put("armBandDistance", valueMap.get("armBandDistance") + "");
			return;
		}
		if("threeFour".equals(itemKey)){
			templateMap.put("distance1",valueMap.get("distance1") + "");
			templateMap.put("distance2", valueMap.get("distance2") + "");
			templateMap.put("protectiveBaffleHigh", valueMap.get("protectiveBaffleHigh") + "");
			return;
		}
		if("threeFive".equals(itemKey)){
			templateMap.put("horizontalDistance",valueMap.get("horizontalDistance") + "");
			templateMap.put("verticalDistance", valueMap.get("verticalDistance") + "");
			return;
		}
		if("fourOne".equals(itemKey)){
			templateMap.put("distance3",valueMap.get("distance3") + "");
			return;
		}

		if("fourTwoOne".equals(itemKey)){
			templateMap.put("spHeight",valueMap.get("spHeight") + "");
			templateMap.put("extLength", valueMap.get("extLength") + "");
			return;
		}
		if("fourTwoTwo".equals(itemKey)){
            if("1".equals(valueMap.get("isAdjacent"))){
                templateMap.put("isAdjacent","是 √ \n" +
                        "否 □");
            }else if("2".equals(valueMap.get("isAdjacent"))){
                templateMap.put("isAdjacent","是 □ \n" +
                        "否 √");
            }else{
                templateMap.put("isAdjacent","是 □ \n" +
                        "否 □");
            }
			templateMap.put("outerCpWidth", valueMap.get("outerCpWidth") + "");
			templateMap.put("leDistance", valueMap.get("leDistance") + "");
			return;
		}
		if("fourTwoThree".equals(itemKey)){
            if("1".equals(valueMap.get("isHave"))){
                templateMap.put("isHave","有 √ \n" +
                        "无 □");
            }else if("2".equals(valueMap.get("isHave"))){
                templateMap.put("isHave","有 □ \n" +
                        "无 √");
            }else{
                templateMap.put("isHave","有 □ \n" +
                        "无 □");
            }
			templateMap.put("distance4231", valueMap.get("distance4231") + "");
			templateMap.put("distance4232",valueMap.get("distance4232") + "");
			templateMap.put("distance4233", valueMap.get("distance4233") + "");
			templateMap.put("adHeight", valueMap.get("adHeight") + "");
			return;
		}
		if("fourThree".equals(itemKey)){
			templateMap.put("raisedHeight",valueMap.get("raisedHeight") + "");
			return;
		}
		if("fourFour".equals(itemKey)){
			templateMap.put("gap",valueMap.get("gap") + "");
			return;
		}
		if("fourSixOne".equals(itemKey)){
			templateMap.put("sideGap",valueMap.get("sideGap") + "");
			templateMap.put("totalGap",valueMap.get("totalGap") + "");
			return;
		}
		if("fourSixTwo".equals(itemKey)){
			templateMap.put("verticalGap",valueMap.get("verticalGap") + "");
			return;
		}
		if("fourSevenTwo".equals(itemKey)){
			templateMap.put("overhang",valueMap.get("overhang") + "");
			return;
		}
		if("fourSevenThree".equals(itemKey)){
			templateMap.put("rigidity",valueMap.get("rigidity") + "");
			templateMap.put("flexibility",valueMap.get("flexibility") + "");
			return;
		}
		if("fourSevenFour".equals(itemKey)){
			templateMap.put("distance474",valueMap.get("distance474") + "");
			return;
		}
		if("fourSevenFive".equals(itemKey)){
			templateMap.put("distance475",valueMap.get("distance475") + "");
			return;
		}
		if("fourSevenSix".equals(itemKey)){
			templateMap.put("angle1",valueMap.get("angle1") + "");
			templateMap.put("angle2",valueMap.get("angle2") + "");
			return;
		}
		if("fourSevenSeven".equals(itemKey)){
			templateMap.put("epLoc",valueMap.get("epLoc") + "");
			return;
		}
		if("fiveOne".equals(itemKey)){
			templateMap.put("meshDepth",valueMap.get("meshDepth") + "");
			templateMap.put("gap51",valueMap.get("gap51") + "");
			return;
		}
		if("eightTwoOne".equals(itemKey)){
			templateMap.put("runTime",valueMap.get("runTime") + "");
			return;
		}
		if("eightTwoTwo".equals(itemKey)){
			templateMap.put("transTime",valueMap.get("transTime") + "");
			return;
		}
	}


	/**
	 * 液压电梯，处理检查项中填空项
	 * @param templateMap
	 * @param valueMap
	 * @param itemKey
	 */
	private void fillInBlanksHydraulic(Map<String,String> templateMap,Map<String,Object> valueMap,String itemKey){
		if("twoEight".equals(itemKey) || "twoTen".equals(itemKey)
				|| "twoFifteen".equals(itemKey) || "threeFourFour".equals(itemKey)
				|| "fiveOne".equals(itemKey) || "sixTwlve".equals(itemKey)
				|| "sixThreeOne".equals(itemKey) || "sixThreeTwo".equals(itemKey)
				|| "sevenOne".equals(itemKey)){

			if("twoEight".equals(itemKey)){
				templateMap.put("fullLoadPress",valueMap.get("fullLoadPress") + "");
				templateMap.put("reliefValvePress",valueMap.get("reliefValvePress") + "");
				templateMap.put("percent",valueMap.get("percent") + "");
				return;
			}
			if("twoTen".equals(itemKey)){
				templateMap.put("fullLoadPress1",valueMap.get("fullLoadPress1") + "");
				templateMap.put("reliefValvePress1",valueMap.get("reliefValvePress1") + "");
				templateMap.put("multiple",valueMap.get("multiple") + "");
				return;
			}
			if("twoFifteen".equals(itemKey)){
				templateMap.put("nominalVoltage1",valueMap.get("nominalVoltage1") + "");
				templateMap.put("nominalVoltage2",valueMap.get("nominalVoltage2") + "");
				templateMap.put("nominalVoltage3",valueMap.get("nominalVoltage3") + "");
				templateMap.put("insulationResistance1",valueMap.get("insulationResistance1") + "");
				templateMap.put("insulationResistance2",valueMap.get("insulationResistance2") + "");
				templateMap.put("insulationResistance3",valueMap.get("insulationResistance3") + "");
				return;
			}
			if("threeFourFour".equals(itemKey)){
				templateMap.put("inspectTime",valueMap.get("inspectTime") + "");
				templateMap.put("uplinkSpeed",valueMap.get("uplinkSpeed") + "");
				templateMap.put("downlinkSpeed",valueMap.get("downlinkSpeed") + "");
				return;
			}
			if("fiveOne".equals(itemKey)){
				templateMap.put("height",valueMap.get("height") + "");
				return;
			}
			if("sixTwlve".equals(itemKey)){
				templateMap.put("gap",valueMap.get("gap") + "");
				return;
			}
			if("sixThreeOne".equals(itemKey)){
				templateMap.put("gap1",valueMap.get("gap1") + "");
				return;
			}
			if("sixThreeTwo".equals(itemKey)){
				templateMap.put("gap2",valueMap.get("gap2") + "");
				return;
			}
			if("sevenOne".equals(itemKey)){
				templateMap.put("sinkDistance",valueMap.get("sinkDistance") + "");
				return;
			}

		}



	}

	/**
	 * 杂货电梯，处理检查项中填空项
	 * @param templateMap
	 * @param valueMap
	 * @param itemKey
	 */
	private void fillInBlanksImpurity(Map<String,String> templateMap,Map<String,Object> valueMap,String itemKey){
		if("twoOneTwo".equals(itemKey) || "fourFourTwoThree".equals(itemKey)
				|| "fourFourTwoFour".equals(itemKey) || "fiveOneOneFour".equals(itemKey)){
			if("twoOneTwo".equals(itemKey)){
				if("1".equals(valueMap.get("isEnter"))){
					templateMap.put("isEnter","可进入 √ \n" +
							"不可进入 □");
				}else if("2".equals(valueMap.get("isEnter"))){
					templateMap.put("isEnter","可进入 □ \n" +
							"不可进入 √");
				}else{
					templateMap.put("isEnter","可进入 □ \n" +
							"不可进入 □");
				}
				return;
			}

			if("fourFourTwoThree".equals(itemKey)){
				templateMap.put("length",valueMap.get("length") + "");
				return;
			}

			if("fourFourTwoFour".equals(itemKey)){
				templateMap.put("overlapLength",valueMap.get("overlapLength") + "");
				return;
			}

			if("fiveOneOneFour".equals(itemKey)){
				templateMap.put("proportion",valueMap.get("proportion") + "");
				return;
			}

		}
	}


}
